package com.myself.ldap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LdapDemo {
    private static final Hashtable<String, String> ENV = new Hashtable<String, String>();
    private String authentication = null;
    private String driver = null;
    private String password = null;
    private String url = null;
    private String username = null;

    public LdapDemo() {
    }

    public void setAuthentication(String authentication) {
        this.authentication = authentication;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    public static void main(String[] args){
        LdapDemo ldap = new LdapDemo();
        ldap.initLdap();
        System.out.println("结果:"+ldap.jtUserLogin("hanyunfeng@picc.com.cn"));
        System.out.println("结果:"+ldap.jtUserLogin("zhuoyue04@picc.com.cn"));
        System.out.println("结果:"+ldap.jtUserLogin("wuxia@picc.com.cn "));
    }
    public void initLdap() {

        this.driver = "com.sun.jndi.ldap.LdapCtxFactory";
        this.url = "ldap://10.8.18.188:389";
        this.authentication ="simple";
        this.username = "cn=idsinst";
        this.password ="P@SSW0RD2012";

     /*   private static String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
        private static String ldapURL = "ldap://10.8.18.188:389";
        private static String ldapUserName = "cn=idsinst";
        private static String ldapPassWd = "P@SSW0RD2012";
        private static String base = "dc=PICC";*/


        ENV.put(Context.INITIAL_CONTEXT_FACTORY, this.driver);
        ENV.put(Context.PROVIDER_URL, this.url);
        ENV.put(Context.SECURITY_AUTHENTICATION, this.authentication);
        ENV.put(Context.SECURITY_PRINCIPAL, this.username);
        ENV.put(Context.SECURITY_CREDENTIALS, this.password);



    }
    /**
     * 作者：支策
     * 作用：查询总部员工的员工好，排查电商下面个别人比较多的处室。
     * 说明：给工作量统计专用的函数。
     */
    public String jtUserLogin(String mail)
    {
        String org = "hq";
        String base = "cn=users,dc="+org+",DC=PICC";

        List<String> userlist= new ArrayList<String>();
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String rtnAttr[]={"uid","mail",};//员工编码，所属部门uuglobalid，所属部门名称，姓名，用户状态
        sc.setReturningAttributes(rtnAttr);
        DirContext ctx = null;
        NamingEnumeration en = null;
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&(UID=*)&(uuAccountStatus=true)&((mail=" + mail + ")))", sc);
            int i = 0;
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                NamingEnumeration values = sr.getAttributes().getAll();
                Map<String,String> uidMap = new HashMap();
                String uidValue = "";
                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        if(tmp[0].trim().equals("uid")){
                            uidValue = tmp[1].trim();
                        }
                    }
                }
                userlist.add(uidValue);
            }

        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        if(userlist.size() == 0){
            return "错误：未找到用户信息：" + mail;
        }
        if(userlist.size() == 1){
            return userlist.get(0);
        }
        if(userlist.size() > 1){
            return "错误：用户管理系统中发现多个匹配用户：" + mail;
        }
        return "错误：" ;
    }


    /**
     * 作者：支策
     * 作用：查询总部员工的员工好，排查电商下面个别人比较多的处室。
     * 说明：给工作量统计专用的函数。
     */
    public List<String> queryZbUer()
    {
        String org = "hq";
        String base = "cn=users,dc="+org+",DC=PICC";

        // 去除下方几个部分的人员 约 7500 人
        // 北方运营中心/运营管理部
        String bf = "/00000000/201206252220000937hgu4h/201206252219360687j1d0c/2012062522195108907txfk/201206252219530125yk27w/201206252219530265tn484/";
        // 宣武/运营管理部
        String xu = "/00000000/201206252220000937hgu4h/201206252219360687j1d0c/2012062522195108907txfk/20120625221952028191syu/201206252219520375646n8/";
        // 南方运营中心/运营管理部
        String nf = "/00000000/201206252220000937hgu4h/201206252219360687j1d0c/2012062522195108907txfk/20120625221952060923rsj/201206252219520718ih9sn/";
        // 华东运营中心/运营管理部
        String hd ="/00000000/201206252220000937hgu4h/201206252219360687j1d0c/2012062522195108907txfk/201206252219530609yky6o/2012062522195306872l98g/";
        // 销售运营部
        String xs = "/00000000/201206252220000937hgu4h/201206252219360687j1d0c/2012062522195108907txfk/1410333908033/";

        List<String> userlist= new ArrayList<String>();
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String rtnAttr[]={"uid","uuHirDeptIdPath","uuAccountStatus"};//员工编码，所属部门uuglobalid，所属部门名称，姓名，用户状态
        sc.setReturningAttributes(rtnAttr);
        DirContext ctx = null;
        NamingEnumeration en = null;
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&(UID=*)&(uuAccountStatus=true)&(!(uuHirDeptIdPath=" + bf + "))&(!(uuHirDeptIdPath=" + xu + "))&(!(uuHirDeptIdPath=" + nf + "))&(!(uuHirDeptIdPath=" + hd + "))&(!(uuHirDeptIdPath=" + xs + ")))", sc);
            int i = 0;
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                NamingEnumeration values = sr.getAttributes().getAll();
                Map<String,String> uidMap = new HashMap();
                String uidValue = "";
                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        if(tmp[0].trim().equals("uid")){
                            value = tmp[1].trim();
                        }
                    }
                }
                userlist.add(uidValue);
            }
            System.out.println(userlist.size());
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return userlist;
    }
    public String queryLdapOrgId(String uid) {
        String base = "DC=PICC";
        String scope = "";
        String filter = "(&((objectClass=inetOrgPerson))(uid=" + uid + "))";
        SearchControls sc = new SearchControls();
        if (scope.equals("base")) {
            sc.setSearchScope(SearchControls.OBJECT_SCOPE);
        } else if (scope.equals("one")) {
            sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        } else {
            sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        }
        //sc.setReturningAttributes(new String[] { "uuglobalid", "ou" });


        NamingEnumeration ne = null;
        DirContext ctx = null;
        String ret = "";
        try {
            ctx = this.getDirContext();
            ne = ctx.search(base, filter, sc);
            if (ne.hasMore()) {
                SearchResult sr = (SearchResult) ne.next();
                ret = sr.toString();
                String[] strs = ret.split(":");
                String[] dcs = strs[0].split(",");
                int len=dcs.length-1;
                String[] rets = dcs[len].split("=");
                ret = rets[1];
            }
        } catch (NamingException nex) {
            nex.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return ret;
    }

    public boolean modifyByUid(Map<String, String> userMap) {
        if (userMap.get("uid") == null)
            return false;
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("uuOfficePhone", "85178070"));
        // 设置属性
        String name = "DN="+userMap.get("uid");
        DirContext ctx = null;
        try {
            ctx = this.getDirContext();
            ctx.modifyAttributes(name, mods);
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            this.close(ctx);
        }
        return true;
    }

    public Map<String,String> getUidByOrg(String org)
    {
        String base = "cn=users,dc="+org+",DC=PICC";

        Map<String,String> uidMap = new HashMap();
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String rtnAttr[]={"uid"};
        sc.setReturningAttributes(rtnAttr);
        DirContext ctx = null;
        NamingEnumeration en = null;
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&(UID=*))", sc);
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                NamingEnumeration values = sr.getAttributes().getAll();

                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        uidMap.put(tmp[1].trim(), tmp[1].trim());
                    }
                }
            }
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return uidMap;
    }


    /**
     * 根据部门id和更新时间查询用户信息
     *
     * @param
     * @return
     */
    public List<Map<String,String>> getUidByOrg(String org,String time)
    {
        String base = "cn=users,dc="+org+",DC=PICC";
        //Map<String,Map<String,String>> userlistMap = new HashMap<String,Map<String,String>>();
        List<Map<String,String>> userlist= new ArrayList<Map<String,String>>();
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        //String rtnAttr[]={"uid","uuParentId","uuParentName","displayName","uuAccountStatus"};//员工编码，所属部门uuglobalid，所属部门名称，姓名，用户状态
        String rtnAttr[]={"uid","departmentNumber","ou","sn","uuAccountStatus"};
        sc.setReturningAttributes(rtnAttr);
        DirContext ctx = null;
        NamingEnumeration en = null;
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&(UID=*)&(uuAccountStatus=true)&(uulastmodifiedtime>="+time+"))", sc);
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                NamingEnumeration values = sr.getAttributes().getAll();
                Map<String,String> uidMap = new HashMap();
                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        uidMap.put(tmp[0].trim(), tmp[1].trim());
                    }
                }
                userlist.add(uidMap);
            }
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return userlist;
    }


    public Map<String,String> getUuGlobalIdByou(String org,String ou)
    {
        String base = "cn=org,dc="+org+",DC=PICC";
        //Map<String,Map<String,String>> userlistMap = new HashMap<String,Map<String,String>>();
        List<Map<String,String>> userlist= new ArrayList<Map<String,String>>();
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        //String rtnAttr[]={"uid","uuParentId","uuParentName","displayName","uuAccountStatus"};//员工编码，所属部门uuglobalid，所属部门名称，姓名，用户状态
        String rtnAttr[]={"uuGlobalId","ou"};
        sc.setReturningAttributes(rtnAttr);
        DirContext ctx = null;
        NamingEnumeration en = null;
        Map<String,String> uidMap = new HashMap();
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&(ou="+ou+"))", sc);
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                NamingEnumeration values = sr.getAttributes().getAll();
                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        uidMap.put(tmp[0].trim().toLowerCase(), tmp[1].trim());
//						System.out.println(tmp[0].trim()+":"+tmp[1].trim());
                    }
                }
                userlist.add(uidMap);
            }
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return uidMap;
    }




    /**
     * 根据用户UID查询用户基本信息
     *
     * @param uid
     * @return
     */
    public Map<String, String> queryLdapByUid(String uid) {
        Map<String, String> userMap = new HashMap<String, String>();
        String base = "DC=PICC";
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        DirContext ctx = null;
        NamingEnumeration en = null;
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&((objectClass=inetOrgPerson))(UID=" + uid+"))", sc);
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                Attributes ab = sr.getAttributes();
                NamingEnumeration values = ab.getAll();
                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        userMap.put(tmp[0], tmp[1]);
                    }
                }
            }
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return userMap;
    }


    /**
     * 根据属性type查询部门信息
     *
     * @param
     * @return
     */
    public Map<String, String> queryLdapByGlobalId(String id,String type) {
        Map<String, String> orgMap = new HashMap<String, String>();
        String base = "DC=PICC";
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        DirContext ctx = null;
        NamingEnumeration en = null;
        try {
            ctx = this.getDirContext();
            en = ctx.search(base, "(&((objectClass=organizationalUnit))("+type+"="+id+"))", sc);
            while (en.hasMore()) {
                SearchResult sr = (SearchResult) en.next();
                Attributes ab = sr.getAttributes();
                NamingEnumeration values = ab.getAll();
                while (values.hasMore()) {
                    String value = values.next().toString();
                    if (null != value && !"".equals(value)) {
                        String[] tmp = value.split(":");
                        orgMap.put(tmp[0], tmp[1]);
                    }
                }
            }
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            this.close(ctx);
        }
        return orgMap;
    }
    private DirContext getDirContext() throws NamingException {
        DirContext ctx = new InitialDirContext(ENV);
        return ctx;
    }

    private void close(DirContext ctx) {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}
